//
//  MainViewController.swift
//  微博练习
//
//  Created by 戚轶鋆 on 16/4/18.
//  Copyright © 2016年 戚轶鋆. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        setTabbarItem()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(addButton)
        
        let width = tabBar.bounds.width / CGFloat(childViewControllers.count)
        
        addButton.frame = CGRectInset(tabBar.bounds, (width - 1) * 2, 0)
    }

    //Mark:-私有属性
    private lazy var addButton:UIButton = {
        let button = UIButton()
        
        let imageName = "tabbar_compose_icon_add"
        button.setImage(UIImage(named: imageName), forState: .Normal)
        button.setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted)
        
        let backImageName = "tabbar_compose_button"
        button.setBackgroundImage(UIImage(named: backImageName), forState: .Normal)
        button.setBackgroundImage(UIImage(named: backImageName + "_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        
        return button
    }()

}



//MARK:-设置tabbar背景图片
extension MainViewController{
    private func setTabbarItem() {
        
        tabBar.shadowImage = UIImage.qy_singleDotImage(UIColor(white: 0.9, alpha: 1))
        tabBar.backgroundImage = UIImage(named: "tabbar_background")
        
        //添加按钮
        tabBar.addSubview(addButton)
        
    }
}

//MARK:-添加nav控制器
extension MainViewController {
    
    //统一添加
    private func addChildViewControllers(){
        
        addChildViewController(HomeViewController(), imageName: "tabbar_home", title: "首页")
        addChildViewController(MessageViewController(), imageName: "tabbar_message_center", title: "消息")
        
        //增加空白页占位
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverViewController(), imageName: "tabbar_discover", title: "发现")
        addChildViewController(ProfileViewController(), imageName: "tabbar_profile", title: "我")
    }
    
    
    //添加子控制器函数
    private func addChildViewController(vc:UIViewController, imageName:String, title:String) {
//        let vc = HomeViewController()
        vc.title = title
        
        //设置文字属性
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: .Selected)
        
        
        //设置图片
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.imageWithRenderingMode(.AlwaysOriginal)
        
        
        
        let nav = UINavigationController(rootViewController:vc)
        
        addChildViewController(nav)
    }
}